/**
 * 
 */
package org.stars.dao.sqlmapper.macro;

import java.util.Map;

import org.stars.dao.sqlmapper.SqlDefinition;
import org.stars.dao.sqlmapper.SqlInsert;
import org.stars.dao.sqlmapper.SqlMacro;
import org.stars.dao.sqlmapper.SqlMapper;
import org.stars.dao.sqlmapper.SqlSelect;
import org.stars.dao.sqlmapper.typealias.TypeAliasUtils;
import org.stars.util.reflect.BeanUtil;
import org.stars.util.reflect.Getter;

/**
 * @author Francesco Benincasa
 *
 */
@MacroDefinition(body=MacroParam.NOT_ADMITTED, evaluation=MacroEvaluation.SOURCE_PROCESSING)
public class Generate extends MacroBase {

	/* (non-Javadoc)
	 * @see org.stars.dao.sqlmapper.macro.Macro#execute(org.stars.dao.sqlmapper.SqlMapper, org.stars.dao.sqlmapper.SqlDefinition, org.stars.dao.sqlmapper.SqlMacro)
	 */
	@Override
	public ReturnState execute(SqlMapper sqlMapper, SqlDefinition sqlQuery,
			SqlMacro sqlMacro) throws Exception {

		Class<?> inputClazz=TypeAliasUtils.resolveClass(sqlQuery.getParam());
		Map<String, Getter> map=BeanUtil.getGetters(inputClazz);
		String result=null;
				
		
		if (sqlQuery instanceof SqlSelect)
		{
			result=generateQuery(map);
		} else if (sqlQuery instanceof SqlInsert)
		{
			result=generateInsert(map);
		}
				
		sqlMacro.setTemplateText(result);
		sqlMacro.getParts().clear();
		
		
		return ReturnState.EVALUATE_TEMPLATE;
	}
	
	protected String generateQuery(Map<String, Getter> map)
	{
		StringBuilder sb=new StringBuilder();
		String separator="";
		for (Getter item: map.values())
		{
			sb.append(separator+"a."+item.getPropertyName()+" as "+item.getPropertyName());
			separator=" , ";
		}
		
		return sb.toString();
	}
	
	protected String generateInsert(Map<String, Getter> map)
	{
		StringBuilder sb=new StringBuilder();
		String separator="";
		for (Getter item: map.values())
		{
			sb.append(separator+item.getPropertyName()+" as &["+item.getPropertyName()+"]");
			separator=" , ";
		}
		
		return sb.toString();
	}

}
